//
//  EmotionTextView.m
//  Weibo
//
//  Created by Anasue on 9/30/15.
//  Copyright © 2015 vvusu. All rights reserved.
//

#import "EmotionTextView.h"
#import "Emotion.h"
#import "RegexKitLite.h"
#import "EmotionAttachment.h"

@implementation EmotionTextView

- (void)appendEmotion:(Emotion *)emotion
{
    if (emotion.emoji) {
        [self insertText:emotion.emoji];
    }else{
        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithAttributedString:self.attributedText];
        NSInteger insertIndex = self.selectedRange.location;
        EmotionAttachment *attach = [[EmotionAttachment alloc]init];
        attach.emotion = emotion;
        attach.bounds = CGRectMake(0, -3, self.font.lineHeight, self.font.lineHeight);
        NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
        [attributedText insertAttributedString:attachString atIndex:insertIndex];
        [attributedText addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, attributedText.length)];
        self.attributedText = attributedText;
        self.selectedRange = NSMakeRange(insertIndex + 1, 0);

    }
    
//    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
//    if (emotion.code) {
//        NSAttributedString *subString = [[NSAttributedString alloc]initWithString:emotion.emoji];
//        [attributedText appendAttributedString:subString];
//    }else{//表情图片
//        NSTextAttachment *attach = [[NSTextAttachment alloc]init];
//        attach.image = [UIImage imageWithName:[NSString stringWithFormat:@"%@/%@",emotion.directory,emotion.png]];
//        CGFloat imageW = self.font.lineHeight;
//        CGFloat imageH = imageW;
//        attach.bounds = CGRectMake(0, -3, imageW, imageH);
//        NSAttributedString *subString = [NSAttributedString attributedStringWithAttachment:attach];
//        [attributedText appendAttributedString:subString];
//    }
//    [attributedText addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, attributedText.length)];
//    self.attributedText = attributedText;
}

- (NSString *)realText
{
    //创建获取当前的文本
    NSMutableString *string = [NSMutableString string];
    
    //遍历富文本的内容
    [self.attributedText enumerateAttributesInRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        EmotionAttachment *attach = attrs[@"NSAttachment"];
        if (attach) {
            [string appendString:attach.emotion.chs];
        }else{
            NSString *subStr = [self.attributedText attributedSubstringFromRange:range].string;
            [string appendString:subStr];
        }
    }];
    //返回拼接好的string
    return string;
}



@end
